var express = require('express');
var router = express.Router();
const {MessageModel,UserModel,DoctorModel,InqueryModel}=require('../../models/db')
const WebSocket=require('ws')//引入websocket模块
const server=new WebSocket.Server({port:3001})//创建websocket服务
// 监听连接事件
server.on('connection',(socket)=>{
    console.log('客户端已连接');
    socket.on('message',(msg)=>{
        console.log('收到消息',JSON.parse(msg));
        MessageModel.create(JSON.parse(msg))
        socket.send('服务器已收到消息'+msg)
    })
    socket.on('close',()=>{
        console.log('客户端已断开连接');
    })
})
// 获取消息
router.get('/getmsg',async(req,res)=>{
    const {sender,receiver}=req.query
    let query={
        $or:[
            {sender:sender,receiver:receiver},
            {sender:receiver,receiver:sender}
        ]
    }
    console.log(sender,receiver);
    const result=await MessageModel.find(query)
    res.send({code:200,data:result})
})
//用户
router.post('/adduser',async(req,res)=>{
    await UserModel.create(req.body)
    res.send({code:200,msg:'添加成功'})
})
router.get('/getuser',async(req,res)=>{
    const result=await UserModel.find()
    res.send({code:200,data:result})
})
// 医生
router.post('/adddoctor',async(req,res)=>{
    await DoctorModel.create(req.body)
    res.send({code:200,msg:'添加成功'})
})
router.get('/getdoctor',async(req,res)=>{
    const result=await DoctorModel.find()
    res.send({code:200,data:result})
})
// 问诊
router.post('/addinquery',async(req,res)=>{
    await InqueryModel.create(req.body)
    res.send({code:200,msg:'添加成功'})
})
router.get('/getinquery',async(req,res)=>{
    const result=await InqueryModel.find().populate('doctor').populate('user')
    res.send({code:200,data:result})
})

module.exports = router;
